<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言板</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 30px;
        }

        h1, h2 {
            color: #333;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        input, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        textarea {
            resize: vertical;
            min-height: 100px;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #0056b3;
        }

        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .message-item {
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #fafafa;
        }

        .message-nickname {
            font-weight: bold;
            color: #007bff;
            margin-bottom: 5px;
        }

        .message-content {
            margin-bottom: 10px;
            line-height: 1.5;
        }

        .message-time {
            color: #666;
            font-size: 12px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 10px;
        }

        .search-container {
            margin: 20px 0;
            display: flex;
            gap: 10px;
        }

        .search-container input {
            flex: 1;
        }

        .tab-container {
            margin-bottom: 20px;
        }

        .tab-button {
            background-color: #e9ecef;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 4px 4px 0 0;
        }

        .tab-button.active {
            background-color: #007bff;
            color: white;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .message-form {
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>留言板</h1>

    <!-- 标签页 -->
    <div class="tab-container">
        <button class="tab-button active" onclick="openTab('home')">留言列表</button>
        <button class="tab-button" onclick="openTab('post')">发表留言</button>
    </div>

    <!-- 留言列表标签页 -->
    <div id="home" class="tab-content active">
        <!-- 搜索区域 -->
        <div class="search-container">
            <input type="text" id="searchKeyword" placeholder="搜索留言内容或昵称...">
            <button onclick="searchMessages(1)">搜索</button>
            <button onclick="loadMessages(1)">显示全部</button>
        </div>

        <!-- 留言列表 -->
        <div id="messagesList"></div>

        <!-- 分页控件 -->
        <div id="pagination" class="pagination"></div>
    </div>

    <!-- 发表留言标签页 -->
    <div id="post" class="tab-content">
        <div class="message-form">
            <h2>发表新留言</h2>
            <form id="messageForm">
                <div class="form-group">
                    <label for="nickname">昵称 *</label>
                    <input type="text" id="nickname" required>
                </div>

                <div class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email">
                </div>

                <div class="form-group">
                    <label for="content">留言内容 *</label>
                    <textarea id="content" required></textarea>
                </div>

                <button type="submit">提交留言</button>
                <button type="button" onclick="resetForm()">重置</button>
            </form>
        </div>
    </div>
</div>

<script>
    // 当前页面状态
    let currentPage = 1;
    let isSearching = false;
    let currentKeyword = '';

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadMessages(1);

        // 绑定表单提交事件
        document.getElementById('messageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            submitMessage();
        });
    });

    // 切换标签页
    function openTab(tabName) {
        // 隐藏所有标签内容
        const tabContents = document.getElementsByClassName('tab-content');
        for (let i = 0; i < tabContents.length; i++) {
            tabContents[i].classList.remove('active');
        }

        // 移除所有激活按钮样式
        const tabButtons = document.getElementsByClassName('tab-button');
        for (let i = 0; i < tabButtons.length; i++) {
            tabButtons[i].classList.remove('active');
        }

        // 显示当前标签并激活对应按钮
        document.getElementById(tabName).classList.add('active');
        event.currentTarget.classList.add('active');
    }

    // 加载留言列表
    function loadMessages(page) {
        isSearching = false;
        currentPage = page;

        fetch(`/messages?currentPage=${page}&pageSize=5`)
            .then(response => response.json())
            .then(data => {
                displayMessages(data);
            })
            .catch(error => {
                console.error('加载留言失败:', error);
                document.getElementById('messagesList').innerHTML = '<p>加载留言失败，请稍后重试</p>';
            });
    }

    // 搜索留言
    function searchMessages(page) {
        const keyword = document.getElementById('searchKeyword').value.trim();
        if (!keyword) {
            alert('请输入搜索关键词');
            return;
        }

        isSearching = true;
        currentKeyword = keyword;
        currentPage = page;

        fetch(`/messages/search?keyword=${encodeURIComponent(keyword)}&currentPage=${page}&pageSize=5`)
            .then(response => response.json())
            .then(data => {
                displayMessages(data);
            })
            .catch(error => {
                console.error('搜索留言失败:', error);
                document.getElementById('messagesList').innerHTML = '<p>搜索留言失败，请稍后重试</p>';
            });
    }

    // 显示留言列表
    function displayMessages(pageData) {
        const messagesList = document.getElementById('messagesList');

        if (pageData.records.length === 0) {
            messagesList.innerHTML = '<p>暂无留言</p>';
            document.getElementById('pagination').innerHTML = '';
            return;
        }

        let messagesHtml = '';
        pageData.records.forEach(message => {
            messagesHtml += `
                    <div class="message-item">
                        <div class="message-nickname">${message.nickname || '匿名用户'}</div>
                        <div class="message-content">${message.content}</div>
                        <div class="message-time">发布时间: ${formatDate(message.createTime)}</div>
                    </div>
                `;
        });

        messagesList.innerHTML = messagesHtml;
        displayPagination(pageData);
    }

    // 显示分页控件
    function displayPagination(pageData) {
        const pagination = document.getElementById('pagination');

        if (pageData.totalPage <= 1) {
            pagination.innerHTML = '';
            return;
        }

        let paginationHtml = '';

        // 上一页按钮
        if (pageData.pageNumber > 1) {
            paginationHtml += `<button onclick="${isSearching ? 'searchMessages' : 'loadMessages'}(${pageData.pageNumber - 1})">上一页</button>`;
        }

        // 页码信息
        paginationHtml += `<span>第 ${pageData.pageNumber} 页 / 共 ${pageData.totalPage} 页</span>`;

        // 下一页按钮
        if (pageData.pageNumber < pageData.totalPage) {
            paginationHtml += `<button onclick="${isSearching ? 'searchMessages' : 'loadMessages'}(${pageData.pageNumber + 1})">下一页</button>`;
        }

        pagination.innerHTML = paginationHtml;
    }

    // 提交留言
    function submitMessage() {
        const message = {
            nickname: document.getElementById('nickname').value.trim(),
            email: document.getElementById('email').value.trim(),
            content: document.getElementById('content').value.trim()
        };

        // 简单验证
        if (!message.nickname) {
            alert('请输入昵称');
            return;
        }

        if (!message.content) {
            alert('请输入留言内容');
            return;
        }

        // 发送请求
        fetch('/messages', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(message)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('留言成功！');
                    resetForm();
                    loadMessages(1);
                    openTab('home'); // 切换到留言列表标签页
                } else {
                    alert('留言失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('提交留言失败:', error);
                alert('提交留言失败，请稍后重试');
            });
    }

    // 重置表单
    function resetForm() {
        document.getElementById('messageForm').reset();
    }

    // 格式化日期时间
    function formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }
</script>
</body>
</html>
